<template>
  <el-card class="box-card">
    <div style="margin-bottom: 10px; display: flex; align-items: center; justify-content: space-between">
      <div>
        <el-row>
          <el-col :span="8">
            <el-input v-model="urlParams.search" placeholder="请输入关键字" @keyup.enter="onSearch" clearable @clear="onSearch" class="search" />
          </el-col>
          <!--选择服务模块-->
          <el-col :span="5">
            <el-select v-model="urlParams.server" class="m-2" @click="getServer" clearable @clear="onSearch" placeholder="服务模块">
              <el-option v-for="row in server" :key="row.id" :label="row.name" :value="row.id"></el-option>
            </el-select>
          </el-col>
          <!--选择主版本号-->
          <el-col :span="4">
            <el-select v-model="urlParams.master_version" class="m-2" @click="getMasterVersion" clearable @clear="onSearch" placeholder="主版本号">
              <el-option v-for="row in master_version" :key="row.id" :label="row.name" :value="row.id"></el-option>
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-select v-model="urlParams.applicant" class="m-2" @click="getApplicant" clearable @clear="onSearch" placeholder="申请人">
              <el-option v-for="row in applicant" :key="row.name" :label="row.name" :value="row.name"></el-option>
            </el-select>
          </el-col>
          <el-col :span="1" style="margin-left: 5px">
            <el-button type="primary" @click="onSearch">
              <el-icon><search /></el-icon>
              &nbsp;搜索
            </el-button>
          </el-col>
        </el-row>
      </div>
      <div>
        <!--导出excel按钮-->
        <el-button type="primary" @click="handelWorkOrderExcel">导出excel</el-button>
        <el-button type="primary" @click="handelWorkOrderCreate">
          <el-icon><CirclePlus /></el-icon>
          &nbsp;新建工单
        </el-button>
        <!--展示列弹出框-->
        <el-popover placement="left" :width="100" v-model:visible="columnVisible">
          <template #reference>
            <el-button type="primary" @click="columnVisible = true">
              <el-icon><Tools /></el-icon>
              &nbsp;展示列
            </el-button>
          </template>
          <el-checkbox v-model="showColumn.department">部门管理</el-checkbox>
          <el-checkbox v-model="showColumn.project">项目管理</el-checkbox>
          <el-checkbox v-model="showColumn.server">服务模块</el-checkbox>
          <el-checkbox v-model="showColumn.applicant">申请人</el-checkbox>
          <el-checkbox v-model="showColumn.work_order_number">工单号</el-checkbox>
          <el-checkbox v-model="showColumn.fault_description">故障描述</el-checkbox>
          <el-checkbox v-model="showColumn.Fault_cause">故障原因</el-checkbox>
          <el-checkbox v-model="showColumn.modify">如何修改</el-checkbox>
          <el-checkbox v-model="showColumn.reach">影响范围</el-checkbox>
          <el-checkbox v-model="showColumn.version">版本号</el-checkbox>
          <el-checkbox v-model="showColumn.script">脚本</el-checkbox>
          <el-checkbox v-model="showColumn.config">配置</el-checkbox>
          <el-checkbox v-model="showColumn.status">状态</el-checkbox>
          <el-checkbox v-model="showColumn.priority">优先级</el-checkbox>
          <el-checkbox v-model="showColumn.corresponding_working_hours">响应工时</el-checkbox>
          <el-checkbox v-model="showColumn.processing_working_hours">处理工时</el-checkbox>
          <el-checkbox v-model="showColumn.response_time">响应时间</el-checkbox>
          <el-checkbox v-model="showColumn.processing_time">处理时间</el-checkbox>
          <el-checkbox v-model="showColumn.processed_people">处理人</el-checkbox>
          <el-checkbox v-model="showColumn.note">备注</el-checkbox>
          <el-checkbox v-model="showColumn.create_time">创建时间</el-checkbox>
          <el-checkbox v-model="showColumn.update_time">修改时间</el-checkbox>
          <div style="text-align: right; margin: 0">
            <el-button size="small" type="primary" @click="columnVisible = false">取消</el-button>
            <el-button size="small" type="primary" @click="saveColumn">确认</el-button>
          </div>
        </el-popover>
      </div>
    </div>

    <div>
      <!--数据表格-->
      <!--复选框回调函数selection-change-->
      <el-table :data="WorkOrderData" border style="width: 100%" :header-cell-style="{ backgroundColor: '#409EFF', color: '#fff', fontsize: '14px' }" @selection-change="handleSelectionChange">
        <!--添加表格复选框-->
        <el-table-column type="selection"></el-table-column>
        <el-table-column type="index" label="序号" width="55" align="center" />
        <el-table-column prop="department.name" label="部门管理" width="120" v-if="showColumn.department" align="center" />
        <el-table-column prop="project.name" label="项目管理" width="120" v-if="showColumn.project" align="center" />
        <el-table-column prop="server.name" label="服务模块" width="120" v-if="showColumn.server" align="center" />
        <el-table-column prop="master_version.name" label="主版本号" width="120" v-if="showColumn.server" align="center" />
        <el-table-column prop="applicant" label="申请人" width="80" v-if="showColumn.applicant" align="center" />
        <el-table-column prop="work_order_number" label="工单号" v-if="showColumn.work_order_number" align="center" />
        <el-table-column prop="fault_description" label="故障描述" width="160" v-if="showColumn.fault_description" align="center" />
        <el-table-column prop="Fault_cause" label="故障原因" width="90" v-if="showColumn.Fault_cause" align="center" />
        <el-table-column prop="modify" label="如何修改" width="90" v-if="showColumn.modify" align="center" />
        <el-table-column prop="reach" label="影响范围" width="90" v-if="showColumn.reach" align="center">
          <template #default="scope">
            <el-tag class="mx-1" effect="dark" round type="info" v-if="scope.row.reach == '小'">小</el-tag>
            <el-tag class="mx-1" effect="dark" round type="warning" v-if="scope.row.reach == '一般'">一般</el-tag>
            <el-tag class="mx-1" effect="dark" round type="danger" v-if="scope.row.reach == '大'">大</el-tag>
            <el-tag class="mx-1" effect="dark" round type="success" v-if="scope.row.reach == '不影响'">不影响</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="version" label="子版本号" width="90" v-if="showColumn.version" align="center" />
        <el-table-column prop="script" label="脚本" v-if="showColumn.script" align="center" />
        <el-table-column prop="config" label="配置" v-if="showColumn.config" align="center" />
        <el-table-column prop="status" label="状态" v-if="showColumn.status" align="center">
          <template #default="scope">
            <el-tag class="mx-1" effect="dark" round type="info" v-if="scope.row.status == '待分配'">待分配</el-tag>
            <el-tag class="mx-1" effect="dark" round type="danger" v-if="scope.row.status == '作废'">作废</el-tag>
            <el-tag class="mx-1" effect="dark" round type="success" v-if="scope.row.status == '处理中'">处理中</el-tag>
            <el-tag class="mx-1" effect="dark" round  v-if="scope.row.status == '完成'">完成</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" v-if="showColumn.priority" align="center">
          <template #default="scope">
            <el-tag class="mx-1" effect="dark" round v-if="scope.row.priority == '低'">低</el-tag>
            <el-tag class="mx-1" effect="dark" round type="info" v-if="scope.row.priority == '一般'">一般</el-tag>
            <el-tag class="mx-1" effect="dark" round type="warning" v-if="scope.row.priority == '高'">高</el-tag>
            <el-tag class="mx-1" effect="dark" round type="danger" v-if="scope.row.priority == '紧急'">紧急</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="corresponding_working_hours" label="响应工时" width="90" v-if="showColumn.corresponding_working_hours" align="center" />
        <el-table-column prop="processing_working_hours" label="处理工时" width="90" v-if="showColumn.processing_working_hours" align="center" />
        <el-table-column prop="processed_people" label="处理人" v-if="showColumn.processed_people" align="center" />
        <el-table-column prop="note" label="备注" v-if="showColumn.note" align="center" />
        <el-table-column prop="response_time" label="响应时间" width="150" :formatter="dateFormat" v-if="showColumn.response_time" align="center" />
        <el-table-column prop="processing_time" label="处理时间" width="150" :formatter="dateFormat" v-if="showColumn.processing_time" align="center" />
        <el-table-column prop="create_time" label="创建时间" :formatter="dateFormat" width="150" v-if="showColumn.create_time" align="center" />
        <el-table-column prop="update_time" label="修改时间" :formatter="dateFormat" width="150" v-if="showColumn.update_time" align="center" />
        <!--操作栏-->
        <el-table-column label="操作栏" fixed="right" width="140" align="center">
          <!--定义获取行内数据参数-->
          <template #default="scope">
            <!--通过回调函数获取行内数据-->
            <el-button type="primary" size="small" round v-if="scope.row.status != '待分配'" @click="handelWorkOrderEdit(scope.$index, scope.row)">查看</el-button>
            <el-button type="primary" size="small" round v-if="!scope.row.processed_people" @click="handelWorkOrderReceiving(scope.$index, scope.row)">接单</el-button>
            <el-button type="success" size="small" round v-if="scope.row.status == '待分配'" @click="handelWorkOrderAllocation(scope.$index, scope.row)">分配</el-button>
            <el-button type="danger" size="small" round v-permission="['admin',]"  v-if="scope.row.status != '待分配' && scope.row.status != '作废' " @click="handelMyWorkOrderCancel(scope.$index, scope.row)">作废</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!--分页-->
      <div style="margin-top: 20px">
        <el-pagination v-model:currentPage="currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" background @size-change="handleSizeChange" @current-change="handleCurrentChange"></el-pagination>
      </div>
    </div>
  </el-card>
  <!--使用子组件-->
  <WorkOrderAllocation v-model:visible="dialogWorkOrderAllocation" :row="row"></WorkOrderAllocation>
  <WorkOrderCreate v-model:visible="dialogWorkOrderCreate" :row="row"></WorkOrderCreate>
  <!--使用子组件-->
  <WorkOrderEdit v-model:visible="dialogWorkOrderEdit" :row="row"></WorkOrderEdit>
</template>

<script>
// 导入excel工具
import * as XLSX from 'xlsx'
// 导入子组件
import WorkOrderAllocation from './WorkOrderAllocation.vue'
import WorkOrderCreate from './WorkOrderCreate.vue'
// 导入子组件MyWorkOrderEdit编辑
import WorkOrderEdit from './WorkOrderEdit.vue'

export default {
  name: 'WorkOrder',

  // 引用子组件
  components: {
    WorkOrderAllocation,
    WorkOrderCreate,
    WorkOrderEdit
  },
  data() {
    return {
      WorkOrderData: [], // 存放数据表格列表
      username: window.localStorage.getItem('name'), // 获取login保存到会话存储的username
      selectWorkOrder: [], // 选择复选框选择的记录存储在这个集合里

      // ================================ 分页配置 ============
      currentPage: 1, // 默认开始页面
      pageSize: 10, // 默认每页的数据条数
      total: 0, // 总数据条数
      urlParams: {
        // URL查询参数，传递服务端，放这里方便修改值
        page_num: 1,
        page_size: this.pageSize,
        search: '',
        server: '',
        master_version: '',
        applicant: '',
      },
      server: '',
      master_version: '',
      applicant: '',
      // =============================== 通用获取行内数据配置 ===============
      row: '',

      // =============================== 分配配置 ===============
      dialogWorkOrderAllocation: false,

      // ============================== 创建 ===================
      dialogWorkOrderCreate: false,

      // =============================== 编辑配置 ===============
      dialogWorkOrderEdit: false,

      // ============================== 展示列 ==================
      columnVisible: false, // 可展示列显示与隐藏
      showColumn: {
        // 字段默认是否展示
        department: true,
        project: true,
        server: true,
        applicant: true,
        work_order_number: true,
        fault_description: true,
        Fault_cause: true,
        modify: true,
        reach: true,
        version: true,
        script: true,
        config: true,
        status: true,
        priority: true,
        response_time: false,
        processing_time: false,
        corresponding_working_hours: false,
        processing_working_hours: false,
        processed_people: true,
        note: false,
        create_time: false,
        update_time: false
      }
    }
  },
  // 页面渲染完后挂载
  mounted() {
    this.GetAllWorkOrder()
    // 从浏览器本地存储获取历史存储展示
    const columnSet = localStorage.getItem(this.$route.path + '-columnSet')
    // 如果本地有存储就使用
    if (columnSet) {
      this.showColumn = JSON.parse(columnSet)
    }
  },
  // 请求方法
  methods: {
    GetAllWorkOrder() {
      if (!this.urlParams.server) {
        delete this.urlParams.server
      }
      if (!this.urlParams.master_version) {
        delete this.urlParams.master_version
      }
      this.$http.get('api/work_order/', { params: this.urlParams }).then(res => {
        if (res.data.code == 200) {
          // 把获取数据重新赋值到表格
          this.WorkOrderData = res.data.data

          // 把获取的数据总量重新赋值给total
          this.total = res.data.count
          this.$message.success('获取数据成功')
        } else {
          this.$message.info('请求数据接口失败')
        }
      })
    },

    // 查看弹出层
    handelWorkOrderEdit(index, row) {
      // 重新赋值允许打开查看弹出框
      this.dialogWorkOrderEdit = true
      this.row = row
    },

    // 作废标记
    handelMyWorkOrderCancel(index, row) {
      // 重新赋值完成
      row.status = "作废"
      this.$http.put('api/work_order/' + row.id + '/', row).then(res => {
        if (res.data.code == 200) {
          this.$message.success('作废数据成功')
          // 重新获取数据
          this.GetAllMyWorkOrder()
        } else {
          this.$message.info('请求数据接口失败')
        }
      })
    },
    // excel批量导出
    handelWorkOrderExcel(index, row) {
      const data = this.selectWorkOrder
      const now = new Date(); // 创建一个Date对象，它将包含当前日期和时间
      const currentYear = now.getFullYear(); // 获取当前年份
      const currentMonth = now.getMonth() + 1; // 获取当前月份（注意：月份从0开始，所以要加1）
      const currentDay = now.getDate(); // 获取当前日期（天）

      // 格式化日期和时间为 "YYYY-MM-DD HH:MM:SS" 形式
      const formattedDateTime = `${currentYear}-${currentMonth}-${currentDay}`;

      // 转换数据，只保留country字段中的name属性
      const transformedData = data.map(item => ({
        ID: item.id,
        部门管理: item.department.name, // 只取name属性
        项目管理: item.project.name,
        服务模块: item.server.name, 
        主版本号: item.master_version.name, 
        申请人: item.applicant, 
        工单号: item.work_order_number, 
        故障描述: item.fault_description, 
        故障原因: item.Fault_cause, 
        如何修改: item.modify, 
        影响范围: item.reach, 
        子版本号: item.version, 
        脚本: item.script, 
        配置: item.config, 
        回滚原因: item.fallback, 
        状态: item.status, 
        优先级: item.priority, 
        处理人: item.processed_people, 
        备注: item.note, 
        响应工时: item.corresponding_working_hours, 
        处理工时: item.processing_working_hours, 
        响应时间: item.response_time, 
        处理时间: item.processing_time, 
        创建时间: item.create_time, 
        修改时间: item.update_time, 
      }));
      // 创建一个工作簿
      const workbook = XLSX.utils.book_new()
      const worksheet = XLSX.utils.json_to_sheet(transformedData)

      // 将工作表添加到工作簿
      XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')

      // 生成Excel文件
      XLSX.writeFile(workbook, 'work_order' + '-' + formattedDateTime + '.xlsx')
    },

    // 新建工单
    handelWorkOrderCreate() {
      // 重新赋值允许打开创建弹出框
      this.dialogWorkOrderCreate = true
    },

    // 搜索查询
    onSearch() {
      // 获取搜索后的数据
      this.GetAllWorkOrder()
    },

    // 接单
    handelWorkOrderReceiving(index, row) {
      // 重新赋值申请人
      row.processed_people = this.username
      row.status = '处理中'
      this.$http.put('api/work_order/' + row.id + '/', row).then(res => {
        if (res.data.code == 200) {
          this.$message.success('获取数据成功')
          // 重新获取数据
          this.GetAllWorkOrder()
        } else {
          this.$message.info('请求数据接口失败')
        }
      })
    },

    // 分配
    handelWorkOrderAllocation(index, row) {
      // 重新赋值允许打开编辑弹出框
      this.dialogWorkOrderAllocation = true
      this.row = row
    },

    // 展示列事件调用
    saveColumn() {
      // 将可显示的字段存储到浏览器本地存储, 使用路由+key保存唯一key值
      localStorage.setItem(this.$route.path + '-columnSet', JSON.stringify(this.showColumn))
      // 关闭展示列
      this.columnVisible = false
    },
    // 分页：监听【选择每页数量】的事件
    handleSizeChange(pageSize) {
      // console.log(pageSize)
      this.pageSize = pageSize // 重新设置分页显示
      this.urlParams.page_size = pageSize // 将最新值设置到数据里，用于下面用新值重新获取数据
      this.GetAllWorkOrder()
    },

    // 分页：监听【点击页码】的事件
    handleCurrentChange(currentPage) {
      // console.log(currentPage)
      this.currentPage = currentPage // 重新设置分页显示
      this.urlParams.page_num = currentPage
      this.GetAllWorkOrder()
    },

    // 选择复选框时触发的操作, 把数据回填到列表
    handleSelectionChange(data) {
      // 把选择复选框时触发的函数数据存储到定义集合里
      this.selectWorkOrder = data
    },

    getServer() {
      this.$http.get('api/server/?page_size=1000').then(res => {
        this.server = res.data.data
      })
    },
    getMasterVersion() {
      this.$http.get('api/master_version/?page_size=1000').then(res => {
        this.master_version = res.data.data
      })
    },
    getApplicant() {
      this.$http.get('api/user/?page_size=1000').then(res => {
        this.applicant = res.data.data
      })
    },
    // drf返回时间戳进行转换为标准显示格式
    dateFormat(row, col) {
      let data = row[col.property]
      if (data == null) {
        return ''
      }

      let currDate = new Date(data)
      // 例如 2022-8-15 10:21:30
      let getMonth = currDate.getMonth() + 1
      let getDay = currDate.getDate()
      let getHours = currDate.getHours()
      let getMinutes = currDate.getMinutes()
      let getSeconds = currDate.getSeconds()
      if (getMonth < 10) {
        getMonth = '0' + getMonth
      }
      if (getDay < 10) {
        getDay = '0' + getDay
      }
      if (getHours < 10) {
        getHours = '0' + getHours
      }
      if (getMinutes < 10) {
        getMinutes = '0' + getMinutes
      }
      if (getSeconds < 10) {
        getSeconds = '0' + getSeconds
      }
      // 组合进行返回时间操作
      return currDate.getFullYear() + '-' + getMonth + '-' + getDay + ' ' + getHours + ':' + getMinutes + ':' + getSeconds
    }
  }
}
</script>

<style >
.el-checkbox__input.is-checked .el-checkbox__inner {
  background: #67C23A;
}
</style>
